<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" class="login-form">
      <h3 class="title">实验室管理系统</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
        </el-button>
      </el-form-item>
      <div style="float: right">
        <el-button type="primary" @click="registerDialog">注册</el-button>
      </div>
    </el-form>

    <el-dialog title="用户注册" :visible.sync="dialogFormVisibleRegister" width="800px" center>
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="名字" prop="studentName">
          <el-input v-model="ruleForm.studentName" />
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="ruleForm.studentId" />
        </el-form-item>
        <el-form-item label="手机" prop="studentTel">
          <el-input v-model="ruleForm.studentTel" />
        </el-form-item>
        <el-form-item label="邮箱" prop="studentEmail">
          <el-input v-model="ruleForm.studentEmail" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码" prop="oncePassword">
          <el-input v-model="ruleForm.oncePassword" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="照片">
          <el-upload
            class="avatar-uploader"
            :on-change="getFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="性别" prop="studentSex">
          <el-radio-group v-model="ruleForm.studentSex">
            <el-radio label="男" />
            <el-radio label="女" />
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">注册</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2019-2020 steakLiu</span>
    </div>
  </div>
</template>

<script>
import { register } from '../../api/user'
export default {
  name: 'Login',
  data() {
    return {
      imageUrl: '',
      imgBase64: [],
      ruleForm: {
        studentName: '',
        studentId: '',
        studentTel: '',
        studentSex: '',
        password: '',
        oncePassword: '',
        studentEmail: ''
      },
      rules: {
        studentName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        studentId: [
          { required: true, message: '请输入学号', trigger: 'blur' }
        ],
        studentTel: [
          { required: true, message: '请输入电话号码', trigger: 'blur' }
        ],
        studentSex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ],
        oncePassword: [
          { required: true, message: '请再次输入密码', trigger: 'change' }
        ],
        studentEmail: [
          { required: true, message: '请输入邮箱', trigger: 'change' }
        ]
      },

      formLabelWidth: '120px',

      loginForm: {
        username: '',
        password: ''
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      dialogFormVisibleRegister: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
  },

  methods: {
    getFile(file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.getBase64(file.raw).then(res => {
        this.imgBase64 = res
      })
    },

    getBase64(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function() {
          imgResult = reader.result
        }
        reader.onerror = function(error) {
          reject(error)
        }
        reader.onloadend = function() {
          resolve(imgResult)
        }
      })
    },

    /**
             * 提交注册
             */
    submitForm() {
      if (this.ruleForm.password !== this.ruleForm.oncePassword) {
        this.$message('两次密码不一致')
      } else {
        var sex
        if (this.ruleForm.studentSex === '男') {
          sex = 1
        } else {
          sex = 2
        }
        const params = new URLSearchParams()
        params.append('userId', this.ruleForm.studentId)
        params.append('username', this.ruleForm.studentName)
        params.append('tel', this.ruleForm.studentTel)
        params.append('sex', sex)
        params.append('password', this.ruleForm.password)
        params.append('imgBase64', this.imgBase64)
        params.append('studentEmail', this.ruleForm.studentEmail)
        register(params).then(res => {
          this.$message('注册成功')
          this.dialogFormVisibleRegister = false
        })
      }
    },

    registerDialog() {
      this.dialogFormVisibleRegister = true
    },
    handleLogin() {
      const params = new URLSearchParams()
      params.append('userId', this.loginForm.username)
      params.append('password', this.loginForm.password)
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', params)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },
  getOtherQuery(query) {
    return Object.keys(query).reduce((acc, cur) => {
      if (cur !== 'redirect') {
        acc[cur] = query[cur]
      }
      return acc
    }, {})
  },

  handleAvatarSuccess(res, file) {
    this.imageUrl = URL.createObjectURL(file.raw)
  },
  beforeAvatarUpload(file) {
    const isJPG = file.type === 'image/jpeg'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
      this.$message.error('上传头像图片只能是 JPG 格式!')
    }
    if (!isLt2M) {
      this.$message.error('上传头像图片大小不能超过 2MB!')
    }
    return isJPG && isLt2M
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    /*background-image: url("../assets/image/login-background.jpg");*/
    background-color: #34bfa3;
    background-size: cover;
  }

  .title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
  }

  .login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 5px 25px;

    .el-input {
      height: 38px;

      input {
        height: 38px;
      }
    }

    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 2px;
    }
  }

  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }

  .login-code {
    width: 33%;
    height: 38px;
    float: right;

    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }

  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
